package com.chen.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chen.reggie.common.Result;
import com.chen.reggie.entity.User;
import com.chen.reggie.service.UserService;
import com.chen.reggie.utils.SendSms;
import com.chen.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送腾讯云短信验证
     *
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/sendMsg")
    public Result<String> sendMsg(@RequestBody User user, HttpSession session) {
        log.info("phone->{}", user.toString());
        if (StringUtils.isNotEmpty(user.getPhone())) {
            String ValidateCode = "" + ValidateCodeUtils.generateValidateCode(4);
            log.info("验证码：{}", ValidateCode);
//           SendSms.senMessage("+86" + user.getPhone(), ValidateCode, "5");

            //保存到session在不同的请求中都可以获取
//            session.setAttribute(user.getPhone(), ValidateCode);

            //将生成的验证码缓存到Redis中，并设置有效期为五分钟
            redisTemplate.opsForValue().set(user.getPhone(),ValidateCode,5, TimeUnit.MINUTES);

            return Result.success("短信发送成功");
        }

        return Result.success("短信发送失败");
    }

    /**
     * 移动端用户登录
     *
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/login")
    public Result<User> sendMsg(@RequestBody Map map, HttpSession session) {
        log.info("phone->{}", map.toString());

        //获取手机号
        String phone = map.get("phone").toString();

        //获取验证码
        String code = map.get("code").toString();

        //从session中获取保存的验证码
        Object codeInSession = session.getAttribute(phone);

        //从Redis中获取缓存的验证码
        Object  codeRedis = (String) redisTemplate.opsForValue().get(phone);

        //进行验证码比对（页面提交的验证码和session中保存的验证码比对）
        if (codeRedis != null && codeRedis.equals(code)) {
            //如果能够比对成功，说明登录成功
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone, phone);

            User user = userService.getOne(queryWrapper);
            if (user == null) {
                //判断当前手机号对应的用户是否为新用户
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            session.setAttribute("user",user.getId());

            //如果登录成功,删除Redis中缓存的验证码
            redisTemplate.delete(phone);

            return Result.success(user);


        }


        return Result.error("登录失败");
    }
}
